package br.gerador;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import br.annotations.Coluna;
import br.annotations.Tabela;
import br.interfaces.Persistente;

public abstract class Gerar {

	public static void geraInsert(Persistente persistente) {
		try {
			StringBuilder insert = new StringBuilder("insert into ");
			StringBuilder colunas = new StringBuilder(" ( ");
			StringBuilder valores = new StringBuilder(" ( ");
			Tabela tabela = (Tabela) persistente.getClass().getAnnotation(Tabela.class);
			insert.append(tabela.nome());
			Field[] campos = persistente.getClass().getDeclaredFields();
			for (int i = 0; i < campos.length; i++) {
				Coluna coluna =  (Coluna) campos[i].getAnnotation(Coluna.class);
				if (coluna != null) {
					colunas.append(coluna.nome()+", ");
					valores.append(campos[i].get(persistente)+", ");
				}
			}

			if(colunas.length() > 2) {
				colunas.delete(colunas.length()-2, colunas.length()-1);
			}
			if(valores.length() > 2) {
				valores.delete(valores.length()-2, valores.length()-1);
			}
			colunas.append(")");
			valores.append(")");
			System.out.println(insert.append(colunas).append(" values ").append(valores));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void geraSelect(Persistente persistente) {
		try {
			Tabela tabela = (Tabela) persistente.getClass().getAnnotation(Tabela.class);
			StringBuilder select = new StringBuilder("select");
			StringBuilder colunas = new StringBuilder(" ");
			StringBuilder where = new StringBuilder(" ");
			List<String> valores = new ArrayList<String>();
			Field[] campos = persistente.getClass().getDeclaredFields();
			for (int i = 0; i < campos.length; i++) {
				Coluna coluna =  (Coluna) campos[i].getAnnotation(Coluna.class);
				if (coluna != null) {
					colunas.append(coluna.nome()+", ");
					Object valor = campos[i].get(persistente);
					if(valor != null) {
						where.append(coluna.nome()+" = :"+coluna.nome()+" and ");
						valores.add(valor.toString());
					}
				}
			}
			
			if(colunas.length() > 2) {
				colunas.delete(colunas.length()-2, colunas.length()-1);
			}
			if(where.length() > 2) {
				where.delete(where.length()-5, where.length()-1);
			}
			System.out.println(select.append(colunas).append(" from ").append(tabela.nome()).append(" where").append(where));
			for(String s : valores) {
				System.out.println(s);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
